<template>
  <div v-show="visible" class="detail-container w-full h-full absolute top-0 left-0 z-600">
    <BasicDetail v-bind="getBindValues" class="FlowDetail-box" @close="closePage">
      <div class="h-full content px-6 flex flex-col">
        <div class="text-base">
          <Tabs v-model:active-key="activeKey">
            <template v-for="item in flowProcessDesc.flowDataArr" :key="item.id">
              <TabPane :tab="item.name" />
            </template>
          </Tabs>
        </div>

        <ScrollContainer v-show="activeKey === 1">
          <div class="mt-2 mb-6">
            <SectionTitle v-if="flowDataRef.workItemName" :title="flowDataRef.workItemName" />
          </div>
          <BasicForm @register="registerForm" />
        </ScrollContainer>
        <Designer
          v-if="flowDataRef.processXml && activeKey === 2"
          :readOnly="true"
          class="flex-1"
          :flowWorkItemID="flowWorkItemID"
          :xml="flowDataRef.processXml"
          :finishedInfo="flowDataRef.finishedInfo"
          :node-disabled="nodeDisabled"
        />

        <ApprovalInformation v-if="activeKey === 3" :list="flowProcessDesc.processDesc" />
      </div>
      <template #footer>
        <div
          class="h-full flow-btn-box flex justify-start items-center"
          v-if="flowDataRef.workItemDto.menus && flowDataRef.workItemDto.menus.length"
        >
          <template v-for="(item, index) in flowDataRef.workItemDto.menus" :key="item.code">
            <div class="flow-btn" :class="{ active: currentBtn === index }" @click="handerFn(item)">
              {{ item.name }}
            </div>
          </template>
        </div>
      </template>
    </BasicDetail>
    <SendFlowModel @register="registerModel" @success="handleSuccess" />

    <!-- 传阅，征询，转批 -->
    <ComFlowModel
      :formScheama="formScheama"
      @register="registerComFlowModel"
      @success="handleSuccessFn"
    />
    <ModelDesign
      v-if="visible && activeKey === 1"
      :classify="2"
      :modelId="btnData.dataModelId"
      @success="initForm"
      :data-modelId="btnData.dataModelId"
    />
  </div>
</template>
<script lang="ts" setup>
  import {
    computed,
    ref,
    useAttrs,
    watch,
    unref,
    watchEffect,
    reactive,
    onUnmounted,
    toRaw,
    nextTick,
  } from 'vue';
  import { BasicDetail } from '/@/components/Detail';
  import { Tabs } from 'ant-design-vue';
  import { tabsData } from './flow-data';
  import { Designer } from '/@/components/BpmnChart';
  import ApprovalInformation from './ApprovalInformation/index.vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { UseModalInit } from '/@/components/ModelTable/src/hooks/useComFormModel';
  import {
    createFlowProcessReturnApi,
    sendFlowProcessApi,
    closeFlowProcessApi,
  } from '/@/api/flow/flow';
  import SendFlowModel from './SendFlowModel.vue';
  import { useModal } from '/@/components/Modal';
  import ModelDesign from '/@/components/ModelTable/src/components/ShowModelDesign.vue';
  import { useFlowButton, flowApiFn } from './hooks/useFlowButton';
  import { useInitFlow } from './hooks/useInitFlow';
  import { cloneDeep } from 'lodash-es';
  import { deleteObjAttribute } from './helper';
  import { useFlowStoreWithout } from '/@/store/modules/flow';
  import SectionTitle from './SectionTitle.vue';
  import ComFlowModel from './ComFlowModel.vue';
  import { getBtnFormScheama } from './helper';
  import { ScrollContainer } from '/@/components/Container';

  const TabPane = Tabs.TabPane;

  const props = defineProps({
    visible: Boolean,
    currentBtn: {
      type: Number,
      default: 0,
    },
    nodeDisabled: {
      type: Boolean,
      default: false,
    },
  });

  const emit = defineEmits(['update:visible', 'success', 'change']);

  const loading = ref(false);
  const activeKey = ref(1);
  const btnData = ref<any>();
  const visibleRef = ref(false);
  const flowStore = useFlowStoreWithout();

  const flowDataRef = reactive<any>({
    processXml: '',
    guid: '',
    workItemDto: {},
    workItemName: '',
    moduleId: '',
    finishedInfo: {},
    dataModelId: '',
  });
  const flowCheckParams = ref({
    workItemID: '',
    entryID: '',
  });

  const formScheama = ref();

  const flowProcessDesc = reactive({
    flowDataArr: tabsData,
    isCheck: false, // 是否流程详情
    isManage: false, // 是否流程版办理
    processDesc: [],
  });
  const modalInit = ref<Indexable>({});
  const attrs = useAttrs();

  const getBindValues = computed(() => {
    const values = {
      ...attrs,
      visible: unref(visibleRef),
      loading: loading.value,
    };
    return values;
  });
  const flowWorkItemID = ref<any>('');
  const [registerForm, formActionType] = useForm({
    labelWidth: 110,
    baseColProps: { span: 23 },
    showActionButtonGroup: false,
  });

  const [registerModel, { openModal }] = useModal();

  const [registerComFlowModel, { openModal: openComFlowModal }] = useModal();

  watchEffect(() => {
    visibleRef.value = !!props.visible;
  });

  watch(
    () => unref(visibleRef),
    async (val) => {
      if (val) {
        emit('update:visible', val);
      } else {
        activeKey.value = 1;
        flowDataRef.workItemDto = {
          workItemDto: {},
        };
        flowDataRef.workItemName = '';
      }
    },
  );

  // 打开流程页面
  async function openPage(visible = true, data): Promise<void> {
    visibleRef.value = visible;
    console.log(
      '%copen流程Pagedata===>183： ',
      'background: rgb(23, 197, 237,.6); color: #ff5023; font-size:18px;font-weight:700',
      data,
    );

    flowWorkItemID.value = data?.record?.WorkItemID ?? '';

    const params = cloneDeep(data.fieldsMap);
    btnData.value = cloneDeep(data);
    loading.value = true;
    try {
      await useInitFlow(data, { flowDataRef, flowCheckParams, flowProcessDesc, flowStore });

      btnData.value = Object.assign({}, data, {
        dataModelId: flowDataRef.dataModelId,
        params,
      });
      await nextTick();
      await initForm();
    } catch (e) {
      throw e;
    } finally {
      loading.value = false;
    }
  }

  async function initForm() {
    // 表单模型开启了只读并且是详情才做表单详情解析
    const data =
      flowDataRef.workItemDto.formMap.modelFormDesignInfo.isReadonly && flowProcessDesc.isCheck
        ? {
            ...btnData.value,
            readonly: flowProcessDesc.isCheck,
            partReadonly: flowProcessDesc.isManage,
          }
        : { ...btnData.value };

    modalInit.value = new UseModalInit(
      {
        btnData: { ...data },
        formDesignInfo: flowDataRef.workItemDto.formMap.modelFormDesignInfo,
        retFormDesignInfo: {
          ...data?.record_data,
          ...flowDataRef.workItemDto.formMap.resultMap,
        },
      },
      formActionType,
    );
    await modalInit.value.initialize();
  }

  defineExpose({
    openPage,
  });

  function closePage() {
    emit('update:visible', false);
    emit('change', false);
  }

  let sendLoading = false;
  // 按钮事件
  async function handerFn(item) {
    console.log('send测试提交11', sendLoading);

    if (sendLoading) return;
    sendLoading = true;

    try {
      const { getFieldsValue } = formActionType;

      formScheama.value = getBtnFormScheama(item.code);

      // 流程详情内重置名称和type
      btnData.value.label = item.name;
      btnData.value.eventType = item.code;

      await useFlowButton(
        item.code,
        {
          flowDataRef: toRaw(flowDataRef),
          flowCheckParams: unref(flowCheckParams),
          flowProcessDesc: unref(flowProcessDesc),
          btnItem: btnData.value,
          modalInit: modalInit.value,
        },
        [openModal, emit, openComFlowModal, getFieldsValue],
      );
    } catch (e) {
      sendLoading = false;
      throw e;
    }

    sendLoading = false;
  }

  // 发送
  async function handleSuccess(values, successData) {
    console.log('values233', values, flowDataRef.workItemDto);

    if (sendLoading) return;
    sendLoading = true;

    try {
      const { entryContent, choices, response, workItemName } = values;
      const { isSave, receiverLimitMap, afterSumbitFn } = successData;

      let receiverLimit;

      if (flowDataRef.workItemDto.receiverLimit.length) {
        receiverLimit = flowDataRef.workItemDto.receiverLimit.map((item) => {
          const selectedList = receiverLimitMap.get(`recipients${item.id}_${item.type}`);

          return { ...item, selectedList };
        });

        console.log('receiverLimit2', receiverLimit);
      }

      if (workItemName) {
        flowDataRef.workItemName = workItemName;
      }
      const { guid, moduleId, workItemDto, workItemName: flowFileName } = toRaw(flowDataRef);

      const workItemDtoParam = cloneDeep(workItemDto);

      console.log('flowDataRef', flowDataRef.workItemDto);

      // 去除无用参数
      deleteObjAttribute(workItemDtoParam, ['menus', 'choices', 'recipients', 'receiverLimit']);
      deleteObjAttribute(workItemDtoParam.formMap, 'modelFormDesignInfo');

      const isSaveParams = {
        guid,
        moduleId,
        workItemName: flowFileName,
        workItemDto: workItemDtoParam,
      };

      const isSendParams = {
        ...isSaveParams,
        entryContent,
        choice: choices,
        response,
        item_id: workItemDtoParam.formMap.resultMap && workItemDtoParam.formMap.resultMap.item_id,
        id: workItemDtoParam.formMap.resultMap && workItemDtoParam.formMap.resultMap.id,
        receiverLimit,
      };

      const params = !isSave ? isSendParams : isSaveParams;

      const apiFn = !isSave ? sendFlowProcessApi : createFlowProcessReturnApi;

      await flowApiFn(params, apiFn, emit);

      await afterSumbitFn();
    } catch (err) {
      sendLoading = false;
    }

    sendLoading = false;
  }

  function handleSuccessFn() {
    emit('update:visible', false);
    emit('change', false);
    emit('success');
  }

  // 刷新切换关闭流程
  onUnmounted(async () => {
    if (props.visible && flowCheckParams.value.workItemID && flowStore.getFlowReleaseParams) {
      await closeFlowProcessApi({ ...flowCheckParams.value, guid: flowDataRef.guid });
    }
  });
</script>
<style lang="less" scoped>
  .djs-palette {
    display: none;
  }

  .flow-btn-box {
    .flow-btn {
      width: 120px;
      height: 40px;
      background: @white;
      border-radius: 2px 2px 2px 2px;
      border: 1px solid #d8d8d8;
      margin-right: 24px;
      font-size: 16px;
      color: #999999;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;

      &:hover {
        color: @primary-color;
        border: 1px solid @primary-color;
      }

      &.active {
        color: @white;
        border: none;
        background: @primary-color;
      }
    }
  }

  ::v-deep(.ant-tabs-nav-wrap) .ant-tabs-tab {
    font-size: 16px !important;
  }
</style>
